package com.by.yz.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.by.yz.R;
import com.by.yz.activity.base.BaseActivity;
import com.by.yz.adapter.TopicItemAdapter;
import com.by.yz.common.MFGT;
import com.by.yz.custom.TechnologyTeamDividerItemDecoration;
import com.by.yz.entity.Account;
import com.by.yz.entity.Click;
import com.by.yz.entity.Community;
import com.by.yz.entity.TopicInfo;
import com.by.yz.entity.UserTest;
import com.by.yz.loginUtil.TopicInfoRESTFul;
import com.by.yz.util.IsNetWork;
import com.by.yz.util.Start_End_times;
import com.by.yz.util.ToJSonObject;
import com.cjj.MaterialRefreshLayout;
import com.cjj.MaterialRefreshListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by mrs yang on 2016/10/12.
 */
public class SecondCommunity extends BaseActivity implements View.OnClickListener {
    private MaterialRefreshLayout materialRefreshLayout;
    RecyclerView recyclerView;
    List<TopicInfo> topicList = new ArrayList<TopicInfo>();
    List<TopicInfo> list = new ArrayList<TopicInfo>();
    LinearLayout report_topic_layout;
    LinearLayout gonggao1;
    Community community;
    ImageView commontLogo;
    TextView communityName;
    TextView communityCount;
    TextView repor_bless;// 祝福发表
    TextView td_blesscount;// 祝福话题
    TopicItemAdapter topicItemAdapter;
    String comStr;
    int pag;
    private LinearLayout no_topic;
    int count;
    IsNetWork isNetWork;
    Boolean isFresh;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.common_communicaty_head);
        topicItemAdapter = new TopicItemAdapter(this, topicList);
        community = (Community) getIntent().getSerializableExtra("currentCommunity");
//        initView();
//        initDatas();
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.e("ylj", "onStart");
        Log.e("community", community.toString());
        if (isNetWork.isNetworkAvailable(this)) {
            topicList.clear();
            pag = 0;
            initView();
            initDatas();
        } else {
            //无网络连接情况
            new AlertDialog.Builder(this)
                    .setTitle("提示!")
                    .setIcon(android.R.drawable.ic_dialog_info)
                    .setMessage("检测到您还没开启网络，请开启")
                    .setNegativeButton("取消", null)
                    .setPositiveButton("开启",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog,
                                                    int which) {
                                    startActivity(new Intent(
                                            Settings.ACTION_WIRELESS_SETTINGS));// 进入无线网络配置界面
                                }
                            }).show();
        }
    }
    private void initDatas() {
        Log.e("ylj", "initDatas");
        pag=0;
        getCommunityTopics();
        initRefresh();
    }

    private void initView() {
        Log.e("ylj", "initView");

        gonggao1 = (LinearLayout) findViewById(R.id.Gonggao_lay1);

        setToolbarTitle(community.getCommunityName());
        Log.e("ylj", "comnu" + community.getCommunityName());
        try {
            comStr = URLEncoder.encode(community.getCommunityName(), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Log.e("ylj", "中文转unicode" + comStr);
        commontLogo = (ImageView) findViewById(R.id.common_communicaty_image);
        switch (community.getCommunityName()) {
            case "祝福墙":
                commontLogo.setImageResource(R.mipmap.zhufu_image);
                break;
            case "外科社区":
                commontLogo.setImageResource(R.mipmap.neike_image);
                break;
            case "内科社区":
                commontLogo.setImageResource(R.mipmap.waike_image);
                break;
            case "中医社区":
                commontLogo.setImageResource(R.mipmap.zhongyi_image);
                break;
            default:
                break;
        }

        communityName = (TextView) findViewById(R.id.common_communicaty_textview);
        communityName.setText(community.getCommunityName());

        communityCount = (TextView) findViewById(R.id.today_topic_count);
        TopicInfoRESTFul topicInfoRESTFul = new TopicInfoRESTFul();
        topicInfoRESTFul.getCommunityTopicInfo(comStr, new TopicInfoRESTFul.MyGetCallBack() {
            @Override
            public void ok(JSONArray response) throws JSONException {
                count = response.length();
                communityCount.setText(Integer.toString(count));
            }

            @Override
            public void error(String error) {
                Log.e("ylj", "更新失败" + error);
            }
        });


        gonggao1 = (LinearLayout) findViewById(R.id.Gonggao_lay1);
        gonggao1.setOnClickListener(this);

        if (community.getCommunityName().equals("祝福墙")) {
            repor_bless = (TextView) findViewById(R.id.report_topic);
            td_blesscount = (TextView) findViewById(R.id.today_topic_textview);
            repor_bless.setText("正能量在等您...");
            td_blesscount.setText("祝福帖");
            gonggao1.setVisibility(View.GONE);
        }
        gonggao1.setClickable(true);
        gonggao1.setOnClickListener(this);
        no_topic = (LinearLayout) findViewById(R.id.no_topic);
        recyclerView = (RecyclerView) findViewById(R.id.health_topic_list);
        recyclerView.setLayoutManager(new LinearLayoutManager(recyclerView.getContext()));
        recyclerView.setAdapter(topicItemAdapter);
        recyclerView.addItemDecoration(new TechnologyTeamDividerItemDecoration(this, TechnologyTeamDividerItemDecoration.VERTICAL_LIST));

        materialRefreshLayout = (MaterialRefreshLayout) findViewById(R.id.refresh);
        materialRefreshLayout.setLoadMore(true);//设置上拉

        report_topic_layout = (LinearLayout) findViewById(R.id.repor_topic_alyout);
        report_topic_layout.setOnClickListener(this);

    }

    public void initRefresh() {
        materialRefreshLayout.setMaterialRefreshListener(new MaterialRefreshListener() {
            @Override
            public void onRefresh(final MaterialRefreshLayout materialRefreshLayout) {
                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        isFresh=true;
                        materialRefreshLayout.finishRefresh();
                        getCommunityTopics();
                    }
                }, 1000);

            }

//            public void onfinish() {
//                Toast.makeText(SecondCommunity.this, "刷新完成", Toast.LENGTH_SHORT).show();
//            }

            @Override
            public void onRefreshLoadMore(final MaterialRefreshLayout materialRefreshLayout) {
                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
//                        Toast.makeText(SecondCommunity.this, "加载完成", Toast.LENGTH_SHORT).show();
                        isFresh=false;
                        getCommunityTopics();
                        //通知刷新
                        /**
                         * 完成加载数据后，调用此方法，要不然刷新的效果不会消失
                         */
                        materialRefreshLayout.finishRefreshLoadMore();
                    }
                }, 1000);

            }
        });
    }

    /**
     * 获得社区给定的话题
     */
    public void getCommunityTopics() {

        TopicInfoRESTFul topicInfoRESTFul = new TopicInfoRESTFul();
        topicInfoRESTFul.getCommunityTopicInfo1(comStr, pag, new TopicInfoRESTFul.MyGetCallBack() {
            @Override
            public void ok(JSONArray response) throws JSONException {
                TopicInfo topicInfo;
                pag++;
                try {
                    if (response.length() == 0 && isFresh == true) {
                        Toast.makeText(SecondCommunity.this, "没有可以刷新的数据", Toast.LENGTH_SHORT).show();
                    } else if (response.length() != 0 && isFresh == true) {
                        Toast.makeText(SecondCommunity.this, "刷新" + response.length() + "条数据", Toast.LENGTH_SHORT).show();
                    } else if (response.length() == 0 && isFresh == false) {
                        Toast.makeText(SecondCommunity.this, "没有可以加载的数据", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(SecondCommunity.this, "加载" + response.length() + "条数据", Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {

                }
                Log.e("response.length()",response.length()+"");
                Log.e("pag",pag+"");
                if (response.length() == 0 && pag == 1) {
                    no_topic.setVisibility(View.VISIBLE);
                    materialRefreshLayout.setVisibility(View.GONE);
                } else {
                    no_topic.setVisibility(View.GONE);
                    materialRefreshLayout.setVisibility(View.VISIBLE);
                    for (int i = 0; i < response.length(); i++) {
                        JSONObject jsonObject = response.getJSONObject(i);
                        Log.e("JSONObject["+i+"]",jsonObject.toString());
                        topicInfo = ToJSonObject.jsonToBean(jsonObject.toString(), TopicInfo.class);
                        topicList.add(topicInfo);
                    }
                    topicItemAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void error(String error) {
                Log.e("ylj", "更新失败" + error);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.repor_topic_alyout:
                Bundle bundle = new Bundle();
                bundle.putSerializable("currentCommunity", community);
                if (community != null) {
                    Intent intent = new Intent(this, ReportTopicActivity.class);
                    intent.putExtras(bundle);
                    this.startActivity(intent);

                }
                break;
            case R.id.Gonggao_lay1:
                MFGT.startActivity(this, GonggaoActivity.class);
                break;
        }
    }
}

